package com.york.jobmew.circle.server.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 日志切面
 */
@Aspect
@Component
public class LoggingAspect {

    private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);

    // 定义切点：拦截所有 Controller 中的方法
    @Pointcut("execution(* com.york.jobmew..controller..*(..))")
    public void controllerMethods() {
    }

    // 定义切点：拦截 Service 方法
    @Pointcut("execution(* com.york.jobmew..service..*(..))")
    public void serviceMethods() {
    }

    // 组合切点：拦截 Controller 和  Service 方法
    @Pointcut("(controllerMethods() || serviceMethods())")
    public void loggableMethods() {
    }

    // 定义环绕通知
    @Around("loggableMethods()")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getTarget().getClass().getSimpleName();

        // 判断日志级别是否启用，防止无意义的JSON序列化
        if (logger.isInfoEnabled()) {
            logger.info("Executing method: {}.{}", className, methodName);
        }

        try {
            Object result = joinPoint.proceed();

            // 判断日志级别是否启用，防止无意义的JSON序列化
            if (logger.isInfoEnabled()) {
                logger.info("Method {}.{} executed successfully", className, methodName);
            }
            return result;
        } catch (Exception e) {
            // 判断日志级别是否启用
            if (logger.isErrorEnabled()) {
                logger.error("Error in method {}.{}: {}", className, methodName, e.getMessage());
            }
            throw e;
        }
    }
}